import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Chip,
  CircularProgress,
  Alert
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Refresh as RefreshIcon
} from '@mui/icons-material';
import { api, User, CreateUserData, UpdateUserData } from '../../request';

interface UserManagementProps {
  showNotification: (message: string, severity: 'success' | 'error' | 'warning' | 'info') => void;
}

const UserManagement: React.FC<UserManagementProps> = ({ showNotification }) => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    is_superuser: false
  });
  const [formErrors, setFormErrors] = useState<{[key: string]: string}>({});
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    loadUsers();
  }, []);

  const loadUsers = async () => {
    try {
      setLoading(true);
      const userList = await api.admin.getUsers();
      setUsers(Array.isArray(userList) ? userList : []);
    } catch (error) {
      console.error('Load users error:', error);
      setUsers([]);
      showNotification('加载用户列表失败', 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleAddUser = () => {
    setEditingUser(null);
    setFormData({ username: '', email: '', password: '', is_superuser: false });
    setFormErrors({});
    setDialogOpen(true);
  };

  const handleEditUser = (user: User) => {
    setEditingUser(user);
    setFormData({
      username: user.username,
      email: user.email,
      password: '',
      is_superuser: user.is_superuser
    });
    setFormErrors({});
    setDialogOpen(true);
  };

  const handleDeleteUser = async (userId: number) => {
    if (!window.confirm('确定要删除这个用户吗？')) {
      return;
    }

    try {
      await api.admin.deleteUser(userId);
      showNotification('用户删除成功', 'success');
      loadUsers();
    } catch (error) {
      // 提取错误消息，如果error是Error对象，使用其message属性
      const errorMessage = error instanceof Error ? error.message : '删除用户失败';
      showNotification(errorMessage, 'error');
    }
  };

  const validateForm = () => {
    const errors: {[key: string]: string} = {};
    
    if (!formData.username.trim()) {
      errors.username = '用户名不能为空';
    }
    
    if (!formData.email.trim()) {
      errors.email = '邮箱不能为空';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      errors.email = '邮箱格式不正确';
    }
    
    if (!editingUser && !formData.password.trim()) {
      errors.password = '密码不能为空';
    }
    
    if (formData.password && formData.password.length < 6) {
      errors.password = '密码至少6位';
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }

    setSubmitting(true);
    try {
      if (editingUser) {
        await api.admin.updateUser(editingUser.id, formData);
        showNotification('用户更新成功', 'success');
      } else {
        await api.admin.createUser(formData);
        showNotification('用户创建成功', 'success');
      }
      setDialogOpen(false);
      loadUsers();
    } catch (error) {
      // 提取错误消息，如果error是Error对象，使用其message属性
      const errorMessage = error instanceof Error ? error.message : (editingUser ? '更新用户失败' : '创建用户失败');
      showNotification(errorMessage, 'error');
    } finally {
      setSubmitting(false);
    }
  };

  const getRoleColor = (is_superuser: boolean) => {
    return is_superuser ? 'error' : 'default';
  };

  const getRoleLabel = (is_superuser: boolean) => {
    return is_superuser ? '超级管理员' : '普通用户';
  };

  return (
    <Box>
      <Card>
        <CardContent>
          <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
            <Typography variant="h5" component="h2">
              用户管理
            </Typography>
            <Box>
              <Button
                startIcon={<RefreshIcon />}
                onClick={loadUsers}
                sx={{ mr: 1 }}
                disabled={loading}
              >
                刷新
              </Button>
              <Button
                variant="contained"
                startIcon={<AddIcon />}
                onClick={handleAddUser}
              >
                添加用户
              </Button>
            </Box>
          </Box>

          {loading ? (
            <Box display="flex" justifyContent="center" py={4}>
              <CircularProgress />
            </Box>
          ) : users.length === 0 ? (
            <Alert severity="info">暂无用户数据</Alert>
          ) : (
            <TableContainer component={Paper}>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>ID</TableCell>
                    <TableCell>用户名</TableCell>
                    <TableCell>邮箱</TableCell>
                    <TableCell>角色</TableCell>
                    <TableCell>创建时间</TableCell>
                    <TableCell align="right">操作</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {users.map((user) => (
                    <TableRow key={user.id}>
                      <TableCell>{user.id}</TableCell>
                      <TableCell>{user.username}</TableCell>
                      <TableCell>{user.email}</TableCell>
                      <TableCell>
                        <Chip
                          label={getRoleLabel(user.is_superuser)}
                          color={getRoleColor(user.is_superuser) as any}
                          size="small"
                        />
                      </TableCell>
                      <TableCell>
                        {user.created_at ? new Date(user.created_at).toLocaleString() : '-'}
                      </TableCell>
                      <TableCell align="right">
                        <IconButton
                          size="small"
                          onClick={() => handleEditUser(user)}
                          color="primary"
                        >
                          <EditIcon />
                        </IconButton>
                        <IconButton
                          size="small"
                          onClick={() => handleDeleteUser(user.id)}
                          color="error"
                        >
                          <DeleteIcon />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          )}
        </CardContent>
      </Card>

      {/* 添加/编辑用户对话框 */}
      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>
          {editingUser ? '编辑用户' : '添加用户'}
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            label="用户名"
            value={formData.username}
            onChange={(e) => setFormData({ ...formData, username: e.target.value })}
            error={!!formErrors.username}
            helperText={formErrors.username}
            margin="normal"
            disabled={submitting}
          />
          <TextField
            fullWidth
            label="邮箱"
            type="email"
            value={formData.email}
            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
            error={!!formErrors.email}
            helperText={formErrors.email}
            margin="normal"
            disabled={submitting}
          />
          <TextField
            fullWidth
            label={editingUser ? '新密码（留空不修改）' : '密码'}
            type="password"
            value={formData.password}
            onChange={(e) => setFormData({ ...formData, password: e.target.value })}
            error={!!formErrors.password}
            helperText={formErrors.password}
            margin="normal"
            disabled={submitting}
          />
          <FormControl fullWidth margin="normal" disabled={submitting}>
            <InputLabel>角色</InputLabel>
            <Select
              value={formData.is_superuser.toString()}
              label="角色"
              onChange={(e) => setFormData({ ...formData, is_superuser: e.target.value === 'true' })}
            >
              <MenuItem value="false">普通用户</MenuItem>
              <MenuItem value="true">超级管理员</MenuItem>
            </Select>
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(false)} disabled={submitting}>
            取消
          </Button>
          <Button onClick={handleSubmit} variant="contained" disabled={submitting}>
            {submitting ? <CircularProgress size={20} /> : (editingUser ? '更新' : '创建')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default UserManagement;